$(document).ready(function() {
	DynamicAlertMessages.init();
	FilterLinks.init();
	PlanningDetails.init();
	$('.money').maskMoney({
		symbol: 'R$ ',
		symbolStay: true,
		thousands: '.',
		decimal: ','
	});
	PurchaseToggle.init();
	PayInvoice.init();
	ChangePassword.init();
});

var DynamicAlertMessages = {
	'init' : function() {
		$('.alert button').bind('click', DynamicAlertMessages.hideAlert);
	},
	'hideAlert' : function(e) {
		$(e.target).parent().hide('slow');		
	},
	'isErrorAlert' : function(e) {
		return $(e.target).parent().prop('class').indexOf('error') > 0;
	}
};

var FilterLinks = {
	'filter' : null,
	'init' : function() {
		var ArFilter = location.search.replace('?', '').split('=');
		FilterLinks.filter = ArFilter[1];
		FilterLinks.changeClass();
	},
	'changeClass' : function() {
		if( !FilterLinks.filter ) {
			return $('#currentMonthFilter').attr('class', 'selected');
		}
		$('#'+FilterLinks.filter+'Filter').attr('class', 'selected');
	}
};

var PlanningDetails = {
	'init' : function() {
		PlanningDetails.hideDetails();
		$('#planningDetails').bind('change', PlanningDetails.show);
		if( $('#planningDetails').val != '' ) {
			var e = { 
				target: $('#planningDetails') 
			};
			PlanningDetails.show( e );
		}
	},
	'show' : function( e ) {
		var toShow = location.pathname.indexOf('gain') > -1 ? 'gain': 'spent';
		if( StringUtils.isBlank( $(e.target).val() ) ) {
			return PlanningDetails.hideDetails();
		}
		doRequest('post', Config.Url.application + toShow + 'Planned/ajaxDetails', toShow + 'Planned.id='+$(e.target).val(), PlanningDetails.putPlanningDetails);
	},
	'putPlanningDetails' : function( response ) {
		$('#PlannedDetails').show();
		$('#Planned_EventName').html(response.event.name);
		$('#Planned_EventDescription').html(response.event.description);
		$('#Planned_Value').html( Formater.Double.toMoney(response.value) );
		$('#Planned_Expectation').html( Formater.Date.toLocalDate(response.expectation) );
	},
	'hideDetails' : function() {
		$('#PlannedDetails').hide();
	}
};

var StringUtils = {
	'isBlank' : function(string) {
		return  string == undefined || string == null || string == "";
	},
	'reverse' : function(string) {
		var otherString = '';
        for( var i = string.length-1; i >= 0; i-- ) {
            otherString += string[i];
        }
        return otherString;
	}
};

var Formater = {
	'Double' : {
		'toMoney' : function( value ) {
			value = value.toString();
            var cents = value.indexOf('.') > 0 ? value.substr( value.indexOf('.')+1, value.length ) : '00';
            var reais = value.indexOf('.') > 0 ? value.substr(0, value.indexOf('.')) : value;
            var inversedReais = StringUtils.reverse(reais);
            var decimalCounter = 1;
            reais = '';
            for( var i in inversedReais ) {
                reais += inversedReais[i];
                if( decimalCounter%3 == 0 && decimalCounter != 3 ) {
                    reais += '.';
                    decimalCounter = 0;
                }
                decimalCounter++;
            }
            return 'R$ ' + StringUtils.reverse(reais) + ',' + cents;
		}
	},
	'Date' : {
		'toLocalDate' : function( string ) {
			return new Date(string).toLocaleDateString();
		}
	}
};

var PurchaseToggle = {
	'init' : function() {
		$('#installment').hide();
		$('input[name=spent\\.type]').on('click', PurchaseToggle.toggle);
	},
	'toggle' : function(e) {
		var value = $(e.target).val();
		
		if( value == 'VISTA' ) {
			$('#installment').hide('fast');
		} else {
			$('#installment').show('fast');
		}
	}
};

var PayInvoice = {
        'prefix' : 'PayInvoice_',
		'init' : function() {
			$('a[id^='+PayInvoice.prefix+']').on('click', PayInvoice.showForm);
            $('div[id^=PayForm_] button').on('click', PayInvoice.submit);
            $('.alert.credit-card').hide();
		},
        'showForm' : function(e) {
                var idInvoice = $(e.target).prop('id').replace(PayInvoice.prefix, '');
                $('#PayForm_'+idInvoice).toggleClass('show');
                return false;
        },
        'submit' : function(e) {
                var idInvoice = $(e.target).parent().prop('id').replace('PayForm_', '');
                var date = $('#PayForm_'+idInvoice+' input').val();
                var fundId = $('#PayForm_'+idInvoice+' select').val();
                var url = $('#PayForm_'+idInvoice).prev().prop('href');
                doRequest( 'POST', url, 'invoice.id='+idInvoice +'&spent.spentDay='+date+'&spent.fund.id='+fundId, PayInvoice.callback );
        },
        'callback' : function(response) {
            if( response.statusCode == 200 ) {
                $('.alert.credit-card').attr('class', 'alert alert-success');
                $('.alert.credit-card p').html('Fatura paga com sucesso');
                $('.alert.credit-card').show();
                window.setTimeout(function() { location.href = location.href; }, 1000);
            } else {
                $('.alert.credit-card').attr('class', 'alert alert-error');
                $('.alert.credit-card').show();
                $('.alert.credit-card p').html(response.message);
            }
        }
};

var ChangePassword = {
		'init' : function() {
			$('#changePasswordForm').bind('submit', ChangePassword.changePassword);
			if( location.search.indexOf("messageKey") > -1 ) {
				$('.alert').show();
			}
		},
		'changePassword' : function(e) {
			if( $('input[name=confirmPassword]').val() != $('input[name=newPassword]').val() ) {
				$('.alert').show();
				$('.alert p').html("Nova senha e a confirma&ccedil;&atilde;o n&atilde;o s&atilde;o iguais");
				return false;
			}
		}
};

var OrcamentoChart = function(id, trPrefix) {
    this.id = id;
    this.trPrefix = trPrefix;
    this.other = {
        limit: 10,
        total: 0,
        value: 0,
        reachedTheLimit: function() {
            return this.total >= this.limit;
        }
    };
    this.labels = [];
    this.data = [];
    
    fillChartData(this);

    function fillChartData(instance) {
        $('.chart-table tr[class^=' + trPrefix + ']').each(function() {
            var trClassValues = $(this).prop('class').split('-');
            var percent = trClassValues[2].replace('%', '');
            
            if (!instance.other.reachedTheLimit()) {
                instance.data.push(
                        {label: trClassValues[1], data: percent}
                );
            } else {
                instance.other.value += parseFloat( percent );
            }

            instance.other.total++;
        });

        if (instance.other.reachedTheLimit()) {
            instance.data.push(
                    {label: 'Outros', data: instance.other.value}
            );
        }
        jsonToString(instance.data);
    };

    this.draw = function() {
    	new PizzaChart(this.id, this.data);
    };
};

var PizzaChart = function(selector, data) {
	this.properties = {
        series: {
            pie: {
                show: true,
                tilt: 0.7,
                innerRadius: 0.1,
                label: {
                    formatter: function(label, series) {
                        return "<div class='draggable labelChart' style='color:" + series.color + ";'>" + label + " - " + series.percent.toFixed(2) + "%</div>";
                    }
                }
            }
        },
        legend: {
            show: false
        }
    };

	$.plot(selector, data, this.properties);
	$('.draggable').draggable();
};

var NavigateChart = function(id, json) {
    this.container = $(id);
    this.json = json;
    
    var getLowerTimestamp = function() {
        var lowerTimestamp = null;
        
        for (var fund in json) {
            for( var i in json[fund].data ) {
                var timestamp = json[fund].data[i][0].getTime();
                if (lowerTimestamp === null || lowerTimestamp > timestamp) {
                    lowerTimestamp = timestamp;
                }
            }
        }

        return lowerTimestamp;
    };
    var getHighterTimestamp = function() {
        var highterTimestamp = null;
        
        for (var fund in json) {
            for( var i in json[fund].data ) {
                var timestamp = json[fund].data[i][0].getTime();
                if (highterTimestamp === null || highterTimestamp > timestamp) {
                	highterTimestamp = timestamp;
                }
            }
        }

        return highterTimestamp;
    };
    var getHighterValue = function() {
        var highterValue = null;

        for (var fund in json) {
            for (var i in json[fund].data) {
                
                var value = parseFloat(json[fund].data[i][1]);
                if (highterValue === null || highterValue < value) {
                    highterValue = value;
                }
                
            }
        }
        
        return highterValue * 1.2; // Aumenta 20% o limite
    };

    this.properties = {
        series: {
            lines: {
                show: true
            },
            points: {
            	radius: 3,
            	show: true,
            	fill: true
            },
            shadowSize: 0
        },
        xaxis: {
            mode: 'time',
            timeformat: '%Y-%m',
            zoomRange: [0.1, 0.1],
            panRange: [getLowerTimestamp(), getHighterTimestamp()]
        },
        yaxis: {
            zoomRange: [0.1, 0.1],
            panRange: [0, getHighterValue()]
        },
        zoom: {
            interactive: true
        },
        pan: {
            interactive: true
        }
    };

    function addZoomButton(container, chart) {
        $("<div class='zoom-button' style='left:35px;top:10px'>zoom out</div>")
            .appendTo(container)
            .click(function(event) {
                event.preventDefault();
                chart.zoomOut();
            });
    }

    function addArrows(container, chart, urlImg) {
        $("<img class='navigate-button' src='"+urlImg+"arrow-left.gif' style='left: 35px; top: 50px'>")
                .appendTo(container)
                .click(function(e) {
                    e.preventDefault();
                    chart.pan({left: -100});
                 });
        $("<img class='navigate-button' src='"+urlImg+"arrow-right.gif' style='left: 65px; top: 50px'>")
                .appendTo(container)
                .click(function(e) {
                    e.preventDefault();
                    chart.pan({left: 100});
                 });
        $("<img class='navigate-button' src='"+urlImg+"arrow-up.gif' style='left: 50px;top: 35px'>")
                .appendTo(container)
                .click(function(e) {
                    e.preventDefault();
                    chart.pan({top: -100});
                 });
         $("<img class='navigate-button' src='"+urlImg+"arrow-down.gif' style='left: 50px;top: 65px'>")
                .appendTo(container)
                .click(function(e) {
                    e.preventDefault();
                    chart.pan({top: 100});
                 });        
    };

    function getData() {
    	
        var data = [];
        for (var fund in json) {
            var line = { label: json[fund].label, points: {symbol: "circle"} };
            var points = [];
            for (var i in json[fund].data) {
                var date = json[fund].data[i][0];
                var value = json[fund].data[i][1];
                points.push([date, value]);
            }
            line.data = points;
            data.push(line);
        }
        
        return data;
    };

    this.draw = function(urlImg) {
        var chart = $.plot(this.container, getData(), this.properties);
        addZoomButton(this.container, chart);
        addArrows(this.container, chart, urlImg);
    };
};

var PopJQ = {
    id : 0, 
    init : function(title, content, position) {
        var popJQId = 'PopJQ' + PopJQ.id++;
        var left = position.left > 620 ? position.left-522 : position.left+50;
        
        $('body').append(
            '<div id="'+popJQId+'" class="PopJQ" style="position:absolute; top:'+position.top+'px; left:'+left+'px;">' +
                '<div class="title">'+ title +' <span class="close">&nbsp;</span></div>' +
                '<div class="content">' +
                    content +
                '</div>' +
            '</div>'
        );

        $('#'+popJQId+' .close').bind('click', PopJQ.close);
        $('#'+popJQId).draggable({handle:'.title'});
        return popJQId;
    }, 
    close : function(e) {
        $(e.target).parent().parent().remove();
    }
};

function removeMask(str) {
	return str.replace('R$ ', '').replace('.', '').replace(',', '.');
}

function toDate(stDate) {
	var arDate = stDate.split('/');
	return new Date( arDate[2], arDate[1]-1, arDate[0] );
}

function doRequest( type, url, data, successCallback ) {
	$.ajax({
        type:type,
        url:url,
        data:data,
        success: function(response) {
            successCallback.apply(null, [response]);
        },
        error:function(request, status, errorThrown) {
        	
        }
    });
}

function jsonToString(data){
	console.log( JSON.stringify(data) );
}